import { Names } from './store-name'
import { login, rePassword, logout } from '@/api/auth/index'
import { Session, Local } from "@/utils/storage"
import { RouteRecordRaw } from "vue-router"

export const Key = {
  rememberKey: 'isRemember',
  authTokenKey: 'authToken',
  // userInfoKey: 'userInfo',
}

export const useAuthStore = defineStore(Names.AuthorInfo, {
  state: (): AuthState => {
    return {
      rememberData: Local.get(Key.rememberKey), // 是否记住密码
      authToken: Session.get(Key.authTokenKey), // ssesion
      userInfo: {} as any, // 用户信息
      menuList: [] as string[], //菜单权限
      buttonList: [] as string[], //按钮权限
    }
  },
  actions: {
    //记住密码
    setRememberPwd(data?: LoginData) {
      this.rememberData = data
      if (data) {
        Local.set(Key.rememberKey, data)
      } else {
        Local.remove(Key.rememberKey)
      }
    },

    // 登录操作
    userLogin(loginData: LoginData) {
      return new Promise((resolve, reject) => {
        login(loginData).then((res: any) => {
          console.log('登录操作', res);
          const { data } = res
          const authToken = data.auth_token
          // console.log('res', res, data);
          this.authToken = authToken
          // 保存到session
          Session.set(Key.authTokenKey, authToken)
          resolve(res)
        }).catch((error: any) => {
          reject(error)
        })
      })
    },

    // 重置密码
    resetPassword(changePasswordData: ChangePasswordData) {
      return new Promise((resolve, reject) => {
        rePassword(changePasswordData).then((res: any) => {
          // const { data } = res
          // const accessToken = data.access_token
          // // console.log('accessToken', accessToken);
          // this.accessToken = accessToken
          // // 保存到session
          // Session.set(Key.accessTokenKey, accessToken)
          resolve(res)
        }).catch((error: any) => {
          reject(error)
        })
      })
    },

    //设置用户信息
    setUserInfo(data: UserInfo) {
      this.userInfo = data
      // Local.set(Key.userInfoKey, data)
    },

    // 设置按钮权限
    async setButtonList(data: string[]) {
      this.buttonList = data
    },

    // 设置菜单权限
    async setMenuList(data: RouteRecordRaw[]) {
      this.menuList = data
    },

    // 退出系统
    userLogout() {
      return new Promise((resolve, reject) => {
        logout().then((res: any) => {
          // 重置状态
          this.resetUserState();
          // 前往登录页：重新加载当前页面，如果当前页面是需要登录的，
          // 而上面已经将认证状态清除了，再通过路由前置时，没有令牌，则就会跳转到登录页/login
          // 如果当前页面不需要登录就可以访问，可以继续访问。
          window.location.reload();
          resolve(res);
        }).catch((error: Error) => {
          reject(error);
        });
      });
    },

    // 重置用户状态
    resetUserState() {
      this.authToken = undefined;
      this.userInfo = undefined;
      this.menuList = [];
      this.buttonList = [];

      // 移除本地保存的数据
      // Session.remove(Key.authToken);
      // Session.remove(Key.userInfoKey);
    }
  }
})